package com.xxxx.server.service.impl;

import com.xxxx.server.AdminUtils;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.Menu;
import com.xxxx.server.mapper.MenuMapper;
import com.xxxx.server.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lsh
 * @since 2021-03-07
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    // 通过用户id查询菜单列表
    @Override
    public List<Menu> getMenusByAdminId() {
        //此时security全局对象获取adminId，
        Integer adminId = AdminUtils.getCurrentAdmin().getId();
        // 实现.opsForValue()方法
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 获取key键对应的值。
        List<Menu> menus = (List<Menu>) valueOperations.get("menu_" + adminId);
        // 判断是否为空
        // 如果为空，就去数据库获取
        if(CollectionUtils.isEmpty(menus)){
            menus = menuMapper.getMenusByAdminId(adminId);
            // 并将数据设置到Redis中，方便快速读取
            valueOperations.set("menu_" + adminId,menus);
        }
        return menus;
    }

    // 根据role获取menu
    @Override
    public List<Menu> getMenuWithRole() {
        return menuMapper.getMenuWithRole();
    }

    // 权限组：根据角色获取三级菜单
    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
